//
//  ComboBoxViewController.swift
//  MacStudy
//
//  Created by 30san on 2020/9/22.
//  Copyright © 2020 Dawninest. All rights reserved.
//

import Cocoa

class ComboBoxViewController: NSViewController {

    private lazy var dataSources: [String] = {
        var data = Array<String>()
        for index in 0..<10 {
            data.append("comboBox - \(index)")
        }
        return data
    }()
    
    @IBOutlet weak var comboBox: NSComboBox!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        comboBox.delegate = self
        comboBox.dataSource = self
        comboBox.selectItem(at: 2)
        
        // 允许动态添加
//        comboBox.usesDataSource = false
    }
    
    
    //        should not be called when usesDataSource is set to YES
    @IBAction func remove(_ sender: Any) {
        comboBox.removeItem(at: 0)
    }
    
    @IBAction func add(_ sender: Any) {
        comboBox.insertItem(withObjectValue: "inset", at: 0)
    }
}

extension ComboBoxViewController: NSComboBoxDelegate {
    func comboBoxSelectionDidChange(_ notification: Notification) {
        print("comboBoxSelectionDidChange = \(notification)")
        guard let box = notification.object else {
            return
        }
        let comboBox = box as! NSComboBox
        print("comboBox.indexOfSelectedItem = \(comboBox.indexOfSelectedItem) - comboBox.numberOfItems = \(comboBox.numberOfItems)")
    }
}

extension ComboBoxViewController: NSComboBoxDataSource {
    func numberOfItems(in comboBox: NSComboBox) -> Int {
        return dataSources.count
    }
    
    func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
        return dataSources[index]
    }
}
